<?php

namespace Frieza\Modules\LightTopic\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\model\Content\ContentCategoryLabel as mContentCategoryLabel;
use Doraemon\model\LightTopic\LightTopicInteract as mLightTopicInteract;
use Doraemon\service\admin\LightTopicPrize as sLightTopicPrize;
use Doraemon\service\User;
use Doraemon\service\UserLevel as sUserLevel;
use Doraemon\tools\Msg2Admin;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Frieza\Modules\Topic\Extensions\Widgets\Form;
use Illuminate\Http\Request;
use Encore\Admin\Widgets\Tab;
use Doraemon\tools\ImgUrl;
use Illuminate\Support\MessageBag;
use Doraemon\model\LightTopic\LightTopic as mLightTopic;

class LightTopicController extends Controller
{
    public function index(Request $request, Content $content)
    {
        $message = '！！！筛选项是对已发布内容关联的轻话题进行搜索！搜索前列表默认展示运营创建/编辑过的轻话题';
        $title = '提示';
        $html = Msg2Admin::html($title, $message, 'error');
        return $content
            ->header('轻话题管理')
            ->body($html)
            ->row(self::listAction($request));
    }

    public function listAction($request = [])
    {
        $page = $request['page'] ?? 1;
        $pageSize = $request['per_page'] ?? 20;
        $limit = [($page - 1) * $pageSize, $pageSize];

        $bigDataWhere = [];
        if (isset($request['title']) && !empty($request['title'])) {
            $bigDataWhere['AND']['light_topic_label[~]'] = $request['title'];
        }

        if (isset($request['is_build_self']) && !empty($request['is_build_self'])) {
            $bigDataWhere['AND']['is_build_self'] = $request['is_build_self'];
        }

        if (isset($request['pub_obj_2m']) && !empty($request['pub_obj_2m'])) {
            $bigDataWhere['ORDER']['pub_obj_2m'] = 'DESC';
        }

        if (isset($request['pub_unt_2m']) && !empty($request['pub_unt_2m'])) {
            $bigDataWhere['ORDER']['pub_unt_2m'] = 'DESC';
        }

        if (isset($request['create_time']) && !empty($request['create_time'])) {
            if ($request['create_time']['start']) $bigDataWhere['AND']['light_topic_pub_time[>=]'] = $request['create_time']['start'];
            if ($request['create_time']['end']) $bigDataWhere['AND']['light_topic_pub_time[<=]'] = $request['create_time']['end'];
        }

        $isBigData = false;
        if (!empty($bigDataWhere)) {
            $bigDataWhere['AND']['day'] = date('Ymd', strtotime('-1 day'));
            $bigDataWhere['LIMIT'] = $limit;
            $lightTopicList = mLightTopicInteract::getLightTopicInteract($bigDataWhere);
            if (!empty($lightTopicList)) {
                // 去后端表查询轻话题的id
                $lightTopicIds = mLightTopic::getLightTopicByTitles(array_column($lightTopicList, 'light_topic_label'), ['id', 'title', 'admin_id', 'source']);

                if (!empty($lightTopicIds)) {
                    $lightTopicIdsFormat = [];
                    foreach ($lightTopicIds as $lightTopicId) {
                        $lightTopicIdsFormat[$lightTopicId['title']] = [
                            'id' => $lightTopicId['id'],
                            'admin_id' => $lightTopicId['admin_id'],
                            'source' => $lightTopicId['source'],
                        ];
                    }
                    foreach ($lightTopicList as &$lightTopic) {
                        if ($lightTopicIdsFormat[$lightTopic['light_topic_label']]) {
                            $lightTopic['id'] = $lightTopicIdsFormat[$lightTopic['light_topic_label']]['id'];
                            $lightTopic['admin_id'] = $lightTopicIdsFormat[$lightTopic['light_topic_label']]['admin_id'];
                            $lightTopic['source'] = $lightTopicIdsFormat[$lightTopic['light_topic_label']]['source'];
                        } else {
                            $lightTopic['id'] = 0;
                            $lightTopic['admin_id'] = 0;
                        }
                    }
                }
            }
            unset($bigDataWhere['ORDER'], $bigDataWhere['LIMIT']);
            $lightTopicCount = mLightTopicInteract::getLightTopicInteractListCount($bigDataWhere);
            $isBigData = true;
        } else {
            $lightTopicList = mLightTopic::getLightTopicList('*', $limit);
            if (!empty($lightTopicList)) {
                // 去大数据那边查询交互数据
                $interacts = mLightTopicInteract::getLightTopicInteract([
                    'light_topic_label' => array_column($lightTopicList, 'title'),
                    'day' => date('Ymd', strtotime('-1 day')),
                ]);

                if (!empty($interacts)) {
                    $interactsFormat = [];
                    foreach ($interacts as $interact) {
                        $interactsFormat[$interact['light_topic_label']] = $interact;
                    }

                    foreach ($lightTopicList as &$lightTopic) {
                        $lightTopic['pub_obj_num_td'] = $interactsFormat[$lightTopic['title']]['pub_obj_num_td'];
                        $lightTopic['pub_obj_2m'] = $interactsFormat[$lightTopic['title']]['pub_obj_2m'];
                        $lightTopic['pub_unt_num_td'] = $interactsFormat[$lightTopic['title']]['pub_unt_num_td'];
                        $lightTopic['pub_unt_2m'] = $interactsFormat[$lightTopic['title']]['pub_unt_2m'];
                        $lightTopic['uid'] = $interactsFormat[$lightTopic['title']]['uid'];
                    }
                }
            }

            $lightTopicCount = mLightTopic::getLightTopicCount();
        }

        // 统一双方数据字段
        if ($isBigData && !empty($lightTopicList)) {
            foreach ($lightTopicList as &$lightTopic) {
                $lightTopic['title'] = $lightTopic['light_topic_label'];
                $lightTopic['create_time'] = strtotime($lightTopic['light_topic_pub_time']);
            }
        }

        $prizeList = sLightTopicPrize::getAllPrize();

        $gridModel = new pGridDataModel($lightTopicList, $lightTopicCount, [
            'perPage' => $pageSize
        ]);

        $listGrid = Admin::grid($gridModel, function (Grid $grid) use ($prizeList) {
            $grid->disableExport();
            $grid->disableRowSelector();

            $grid->filter(function (Grid\Filter $filter) {
                $filter->disableIdFilter();
                $filter->expand();
                $filter->column(1 / 3, function ($filter) {
                    $filter->equal('title', '轻话题名称');
                    $filter->equal('is_build_self', '用户自建')->radio([
                        1 => '是',
                        2 => '否'
                    ]);
                });
                $filter->column(1 / 3, function ($filter) {
                    $filter->equal('pub_obj_2m', ' ')->checkbox([
                        1 => '查询60日新增内容数(降序)',
                    ]);
                    $filter->equal('pub_unt_2m', ' ')->checkbox([
                        1 => '查询60日新增参与人数(降序)',
                    ]);
                });
                $filter->column(1 / 3, function ($filter) {
                    $filter->between('create_time', '创建时间')->datetime();
                });
            });

            $grid->column('title', '标题');
            $grid->column('create_time', '创建时间')->display(function () {
                return date('Y-m-d H:i:s', $this->create_time);
            });
            $grid->column('pub_obj_num_td', '内容数')->display(function () {
                return $this->pub_obj_num_td ?? '';
            });
            $grid->column('pub_obj_2m', '60日新增内容数')->display(function () {
                return $this->pub_obj_2m ?? '';
            });
            $grid->column('pub_unt_num_td', '参与人数')->display(function () {
                return $this->pub_unt_num_td ?? '';
            });
            $grid->column('pub_unt_2m', '60日新增参与人数')->display(function () {
                return $this->pub_unt_2m ?? '';
            });
            $grid->column('admin_id', '创建者')->display(function () {
                if (isset($this->source) && $this->source == 2) {
                    return isset($this->admin_id) ? Admin::user()->find($this->admin_id)->name : '';
                } else {
                    $userinfo = User::getBasicUserInfoByCache($this->uid);
                    if (empty($userinfo)) return '';
                    $info = [
                        'uid' => "<a href='/admin/user/Detail/{$this->uid}' target='_blank'>{$this->uid}</a>",
                        '昵称' => $userinfo['nick'],
                        '生产等级' => sUserLevel::getUserLevel($this->uid),
                    ];
                    $content = '';
                    foreach ($info as $key => $value) {
                        $content .= "<div>{$key}：{$value}</div>";
                    }

                    return $content;
                }
            });
            $grid->column('has_prize', '参与有奖')->display(function () use ($prizeList) {
                if ($this->id > 0 && isset($prizeList[$this->id])) {
                    $status = '是';
                } elseif ($this->id > 0 && !isset($prizeList[$this->id])) {
                    $status = '否';
                } else {
                    $status = '';
                }
                return "<a href='/admin/LightTopic/{$this->id}/lightTopicPrize' target='_blank' >$status</a>";
            });
            Admin::script($this->setScript());
            $grid->actions(function ($actions) {
                $actions->disableDelete();
                if (!$actions->row->id) {
                    $actions->disableEdit();
                    $actions->prepend('<p><a class="addLightTopic fa fa-edit" data-title="' . $actions->row->title . '" href="javascript:void(0);">编辑</a></p>');
                }
            });
        });

        return $listGrid->render();
    }

    //添加轻话题页面
    public function edit(Content $content, $id = 0)
    {
        $tab = new Tab();
        if ($id > 0) {
            $title = '编辑轻话题';
        } else {
            $title = '添加轻话题';
        }
        $tab->add("$title", $this->editAction($id));
        return $content
            ->header('轻话题管理')
            ->breadcrumb(
                [
                    'text' => '轻话题列表',
                    'url' => '/LightTopic/index'
                ],
                ['text' => "$title"]
            )
            ->body($tab);
    }

    //添加/修改页面
    private function editAction($id = 0)
    {
        $data = [];
        if ($id > 0) {
            $data = mLightTopic::getLightTopicById($id);
        }

        $form = new Form($data);
        $form->hidden('id', '轻轻话题ID');
        if ($id > 0) {
            $form->text('title', '轻话题标题')->required('轻话题标题必填')->readonly();
        } else {
            $form->text('title', '轻话题标题')->required('轻话题标题必填');
        }
        $form->imgUpload('cover_pic_id', '头图', true, ['imgType' => ImgUrl::APPTYPE_OP, 'imgSize' => ImgUrl::IMAGE_SIZE_OP_ORI])
            ->help('建议尺寸：商业-750*520 社区-750*375');
        $form->imgUpload('share_pic_id', '分享图', true, ['imgType' => ImgUrl::APPTYPE_OP, 'imgSize' => ImgUrl::IMAGE_SIZE_OP_ORI])
            ->setMinImageHeight(168)->setMaxImageHeight(168)->setMinImageWight(168)->setMaxImageWight(168)->help('请上传168（宽） x 168（高）尺寸的图片');

        Admin::script($this->guideScript());
        if ($data['guide']) {
            $guide = "'" . $data['guide'] . "'";
            $form->html("<div id='editor' data-id={$guide} data-content={$guide}></div>");
        } else {
            $form->html("<div id='editor' data-id='' data-content=''></div>");
        };

        $categoryLabel = mContentCategoryLabel::getListFormatKey(0, 1);
        $categoryLabelAll = mContentCategoryLabel::getListFormatKey(0, 0, 0);
        $list = array_keys($categoryLabel);
        $allList = [];
        foreach ($categoryLabelAll as $info) {
            if (in_array($info['p_id'], $list)) {
                $allList[$info['p_id']][$info['id']] = $info['name'];
            }
        }
        $radio = $form->radio('category_first_id', '一级品类')->options($categoryLabel);
        foreach ($categoryLabel as $key => $first) {
            $data = $allList[$key];
            $radio->when('=', $key, function ($form) use ($data) {
                $form->radio('category_second_id', '二级品类')->options($data);
            });
        }
        $form->radio('sort_type', '默认瀑布流')->options(['1' => '热门', '2' => '最新']);
        $form->action('/admin/LightTopic/index/save');

        // 去掉原有的重置提交按钮
        $form->disableSubmit();
        $form->disableReset();

        Admin::script($this->getGuideScript());

        // 自定义提交按钮
        $form->hidden('guide', '轻话题引导语');
        $form->html('<div style="text-align:center;padding-top: 40px" >
            <input class="btn btn-sm btn-info button-1134271147" type="submit" id="light_topic_save" value="提交" style="margin-left: 500px;width: 100px;height: 40px"></div> ');

        return $form;
    }

    //话题保存
    public function save(Request $request)
    {
        $all = $request->all();
        unset($all['base'], $all['link_params'], $all['_token']);
        $all['admin_id'] = Admin::user()->id;

        if (isset($all['id']) && $all['id']) {
            $all['update_time'] = time();
            $id = $all['id'];
            unset($all['id']);
            $result = mLightTopic::edit($id, $all);
        } else {
            $all['create_time'] = time();
            $all['update_time'] = time();
            // 运营自建标识为2
            $all['source'] = 2;
            if (isset($all['title']) && $this->hasSpecialStr($all['title'])) {
                $error = new MessageBag([
                    'title' => '存在特殊符号，请修改名称！'
                ]);
                return back()->with(compact('error'));
            }
            $result = mLightTopic::add($all);
        }

        if ($result) {
            $success = new MessageBag([
                'title' => '保存成功'
            ]);

            return back()->with(compact('success'));

        } else {
            $error = new MessageBag([
                'title' => '提交失败！轻话题已存在'
            ]);
            return back()->with(compact('error'));
        }
    }

    public function addLightTopic(Request $request)
    {
        $params = $request->all();
        $add['title'] = $params['title'];
        $add['create_time'] = time();
        $add['update_time'] = time();
        // 运营编辑的用户自建的轻话题标识为1
        $add['source'] = 1;
        $lightTopicId = mLightTopic::getLightTopicByTitle($params['title'], 'id');
        if (!is_null($lightTopicId) && $lightTopicId > 0) {
            $returnId = $lightTopicId;
        } else {
            $returnId = mLightTopic::add($add);
        }
        return ['id' => $returnId];
    }

    /**
     * @return string
     */
    private function setScript()
    {
        return <<<SCRIPT
    $('.addLightTopic').unbind('click').click(function(){
        var title= $(this).attr('data-title');
        let that = $(this)
        let url = '/admin/LightTopic/addLightTopic/';
        let params = {
            title:title,
        };
        $.post(url, params , function (result) {
            if (result.id > 0) {
                parent.window.location.href = "/admin/LightTopic/index/" + result.id + "/edit";
            } else {
                layer.msg('编辑失败');
            }
        });
    });
    SCRIPT;
    }

    /**
     * 判断是否存在特殊字符，可判断中英文及特殊符号混合串（排除-和_）
     * 存在返回true
     * @param string $str
     * @return boolean
     */
    private function hasSpecialStr($str)
    {
        //$前要加反斜杠
        $specialChars = "~·`!！@#\$￥%^…&*()（）—=+[]{}【】、|\\;:；：'\"“‘,./<>《》?？，。";
        //特殊符号数组
        $specialArr = array();
        $len = mb_strlen($specialChars, 'UTF-8');
        for ($i = 0; $i < $len; $i++) {
            $specialArr[] = mb_substr($specialChars, $i, 1, 'UTF-8');
        }
        //待比较字符串数组
        $arr = array();
        $len = mb_strlen($str, 'UTF-8');
        for ($i = 0; $i < $len; $i++) {
            $arr[] = mb_substr($str, $i, 1, 'UTF-8');
        }
        foreach ($arr as $v) {
            if (in_array($v, $specialArr)) {
                return true;
            }
        }
        return false;
    }

    private function guideScript()
    {
        return <<<SCRIPT
function loadScript(src, callback) {
var script = document.createElement("script");

if(script.addEventListener)
script.addEventListener("load", callback, false);
else if(script.attachEvent)
script.attachEvent("onreadystatechange",
function() { loadScript.callbackIE(callback); });

script.src = src;
document.getElementsByTagName("head")[0].appendChild(script);
}
loadScript.callbackIE = function(callback) {
var target = window.event.srcElement;
if(target.readyState == "loaded")
callback.call(target);
};

// load 30k script.
// Listener.cleanUp is defined at the bottom of drag.js
callback = function() {

editor.init({
            selectRequestUrl: 'https://frieza.haohaozhu.me/api/link/linkmodule',
            submitRequestUrl: 'https://frieza.haohaozhu.me/api/link/linkformat',
            rootNodeId: 'editor'
        });
};

loadScript("/vendor/js/frieza-fe/editor.js", callback);
SCRIPT;
    }

    private function getGuideScript()
    {
        return <<<SCRIPT
          $('#light_topic_save').unbind('click').click(function(){
            var data = document.getElementById('editor').getAttribute('data-content');
            $(".guide").attr("value",data);
          });
SCRIPT;
    }
}
